package cn.hpclub.server.controller.admin;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.model.Brand;
import cn.hpclub.server.service.BrandService;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.QueryHelper;
import cn.hpclub.server.validator.admin.BrandValidator;

public class BrandController extends BaseAdminController<Brand>{
    private static Logger logger = LoggerFactory.getLogger(BrandController.class);

    /**
     * 
     * @Title: list
     * @Description:列表功能，列出所有品牌
     */
    public void list(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();

        QueryHelper helper = BrandService.service.getQueryHelper(searchInfo);
        logger.debug(helper.getSqlExceptSelect());

        findByPageForSearch(helper.getSelect(), helper.getSqlExceptSelect());
        setAttrs(searchInfo);// 这一句话其实多余，因为在getSearchInfo中已经调用一次了。

        render("/admin/brand_list.tpl");
    }

    /**
     * 
     * @Title: add
     * @Description:增加一个新品牌，转到增加页面
     */
    public void add(){
        render("/admin/brand_input.tpl");
    }

    /**
     * 
     * @Title: edit
     * @Description:编辑一个品牌，转到编辑页面
     */
    public void edit(){
        setAttr("brand", Brand.dao.findById(getPara("id")));

        render("/admin/brand_input.tpl");
    }

    /**
     * 
     * @Title: save
     * @Description:保存或者更新
     */
    @Before({ Tx.class, BrandValidator.class })
    public void save(){
        Brand brand = getModel(Brand.class);
        int id = InterfaceUtil.getAdminId();
        // SysUser sysUser = SysUser.dao.findById(id);
        brand.set("operated_by", id);
        brand.set("operated_time", new Date());
        if(getParaToBoolean("isAdd")){
            brand.save();
        } else{
            brand.update();
        }
        redirect("/brand/list");
    }

    /**
     * @Description:删除一个品牌
     * @see cn.esstx.cq.server.controller.admin.BaseAdminController#delete()
     */
    public void delete(){
        deleteById("brand");
    }

    /**
     * 
     * @Title: changeStatus
     * @Description:改变品牌的状态，是否启用
     */
    @Before(Tx.class)
    public void changeStatus(){
        String id = getPara("id");
        String targetStatus = getPara("target_status");
        boolean success = BrandService.service.changeStatus(id, targetStatus);
        if(success){
            if(StrKit.notBlank(targetStatus) && targetStatus.equalsIgnoreCase("1")){
                ajaxJsonSuccessMessage("已启用");
            } else{
                ajaxJsonSuccessMessage("已停用");
            }
        } else{
            ajaxJsonErrorMessage("操作失败");
        }

    }
}
